package com.oren.config;

import com.oren.annotation.WswController;
import com.oren.Bean.WswHandler;
import com.oren.Bean.WswRequest;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**  
* @description controller助手类
* @author  wangshiwei  
* @date   2018年6月22日 下午2:01:34
    
*/
public final class ControllerHelper {
	
	//用户存放请求与处理器的映射关系
	private static final Map<WswRequest,WswHandler> ACTION_MAP=new HashMap<WswRequest,WswHandler>();

	static {
		Set<Class<?>> controllerClassSet=ClassHelper.getControllerClassSet();	
		if(controllerClassSet!=null&&controllerClassSet.size()>0) {
			for (Class<?> controllerClass : controllerClassSet) {
				//判断是否包含controller注解
				if (controllerClass.isAnnotationPresent(WswController.class)) {
					//获取controller类上面的注解
					WswController wswController = controllerClass.getAnnotation(WswController.class);
					String controllerAnValue = wswController.value();
					//判断是否包含Controller字符串
					if (controllerAnValue.indexOf("Controller") != -1) {
						//将Controller替换为空  urlPrefix就是前缀
						String urlPrefix = controllerAnValue.replace("Controller", "").trim();
						//获取controller下面的所有方法
						Method[] methods = controllerClass.getDeclaredMethods();
						for (Method method : methods) {
							String requestMethod = urlPrefix;
							String requestPath = method.getName();
							WswRequest request = new WswRequest(requestMethod, requestPath);
							WswHandler handler = new WswHandler(controllerClass, method);
							ACTION_MAP.put(request, handler);
						}
					}

				}

				/*Method [] methods=controllerClass.getDeclaredMethods();
				if(!ArrayUtil.isNotEmpty(methods)) {
					for (Method method : methods) {
						if(method.isAnnotationPresent(WswAction.class)) {
							//从action中获取url映射
							WswAction wswAction=method.getAnnotation(WswAction.class);
							String mapping=wswAction.value();
							//验证url规则
							if(mapping.matches("\\w+:/\\w*")) {
								//获取请求方法和请求路径
								String[] array=mapping.split(":");
								if(!ArrayUtil.isNotEmpty(array)&& array.length==2) {
									String requestMethod=array[0];
									String requestPath=array[1];
									WswRequest request=new WswRequest(requestMethod,requestPath);
									WswHandler handler=new WswHandler(controllerClass,method);
									ACTION_MAP.put(request, handler);
								}
							}
						}
					}
				}*/
			}
		}
	}
	//获取handler
	public static WswHandler getHandler(String requestMethod,String requestPath) {
		WswRequest request=new WswRequest(requestMethod,requestPath);
		return ACTION_MAP.get(request);		
	}
	
}
